package com.cloud.apis.oss.controller;

import com.cloud.apis.oss.consts.CosConsts;
import com.cloud.apis.core.exception.CustomException;
import com.cloud.apis.oss.utils.CosUtil;
import com.cloud.apis.core.web.R;
import com.cloud.apis.core.web.ServiceCode;
import com.cloud.apis.oss.pojo.form.DeleteCosFileForm;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.IOException;
import java.util.HashMap;
/**
 * COS API相关接口控制器
 *
 * @Author YinXi
 * @Versin 1.0.0
 * @Date 2024/3/25
 */
@Slf4j
@RequestMapping("/cos")
@RestController
@Api(tags = "云存储相关API接口")
public class CosController {
    @Autowired
    private CosUtil cosUtil;

    public CosController() {
        log.info("【CosController】");
    }

    @PostMapping("/uploadCosFile")
    @ApiOperation(value = "文件上传")
    public R uploadCosFile(@RequestParam("files") MultipartFile[] files, @RequestParam("type") String type) {
        if(files==null) {
            return R.error("文件不能为空");
        }
        CosConsts cos = CosConsts.findByKey(type);
        try {
            HashMap map = cosUtil.uploadFile(files, cos);
            return R.ok().put("result", map);
        } catch (IOException e) {
            throw new CustomException(ServiceCode.ERROR_CONFLICT.getValue(), e.getMessage());
        }
    }
    @PostMapping("/deleteCosFile")
    @ApiOperation(value = "删除文件")
    public R deleteCosFile(@Valid @RequestBody DeleteCosFileForm form) {
        cosUtil.deleteFile(form.getPathes());
        return R.ok();
    }

}
